<?php
namespace Plu\Library\Models\Platform\Media;

use Phalcon\Mvc\Model,
    Phalcon\Db\Column;

class MediaFavorite extends Model {
    public $Id;

    public $UserId;

    public $MediaId;

    public $CreateTime;

    public function initialize() {
        $this->setReadConnectionService('db.platform.slave');
        $this->setWriteConnectionService('db.platform');
    }

    public function getSource() {
        return 'MediaFavorite';
    }

    public static function getItem($uid, $mediaId) {
        $item = self::findFirst(array(
            "UserId = :uid: AND MediaId = :mediaId:",
            "bind" => array(
                'uid'	  => $uid,
                'mediaId' => $mediaId
            ),
            'bindTypes' => array(
                'uid'		=> Column::BIND_PARAM_INT,
                'mediaId'	=> Column::BIND_PARAM_INT,
            )
        ));

        return $item;
    }

    public static function addFavorite($uid, $mediaId) {
        $item = self::getItem($uid, $mediaId);

        if ($item != false) {
            return false;
        }

        $item = new MediaFavorite;
        $item->UserId = $uid;
        $item->MediaId = $mediaId;
        $item->CreateTime = time();

        return $item->save();
    }

    public static function removeFavorite($uid, $mediaId) {
        $item = self::getItem($uid, $mediaId);

        if ($item != false) {
            return $item->delete();
        }

        return false;
    }

    public static function getFavoritesList($uid, $offset = 0, $limit = 20) {
        $params = array(
            'columns' => 'MediaId, CreateTime',
            'UserId = :uid:',
            'bind' => array(
                'uid' => $uid
            ),
            'bindTypes' => array(
                'uid' => Column::BIND_PARAM_INT
            ),
            'order'	=> "Id DESC"
        );
        $totalCount = intval( self::count($params) );
        $items		= array();

        if ($totalCount > 0) {
            $params['limit'] = $limit;
            $params['offset'] = $offset;

            $data  = self::find($params);
            $items = $data->toArray();
        }

        return array($totalCount, $items);
    }
}
?>
